package com.verlet.springbootdemo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * Jackson 工具类
 *
 * @author Verlet
 * @date 2023-08-22 01:22
 */
@Slf4j
public class ObjectMapperUtils {

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();


    /**
     * 对象转为JSON 格式字符串
     */
    public static String parseJsonStr(@NonNull Object msg) {
        try {
            return OBJECT_MAPPER.writeValueAsString(msg);
        } catch (JsonProcessingException e) {
            log.error("JSON 转化错误", e);
        }
        return "";
    }

    /**
     * JSON 格式字符串转对象
     */
    public static <T> T toBean(String msg, Class<T> clazz) {
        try {
            return OBJECT_MAPPER.readValue(msg, clazz);
        } catch (IOException e) {
            log.error("JSON 解析错误", e);
        }
        return null;
    }
}
